package com.demo.tableversion.service.impl;

import com.demo.tableversion.entity.MetaField;
import com.demo.tableversion.entity.MetaFieldHistory;
import com.demo.tableversion.mapper.MetaFieldHistoryMapper;
import com.demo.tableversion.mapper.MetaFieldMapper;
import com.demo.tableversion.service.IMetaFieldService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 字段元数据 服务实现类
 * </p>
 *
 * @author yl
 * @since 2021-07-16
 */
@Service
public class MetaFieldServiceImpl implements IMetaFieldService {

    @Autowired
    private MetaFieldMapper metaFieldMapper;
    @Autowired
    private MetaFieldHistoryMapper metaFieldHistoryMapper;

    @Override
    public int saveMetaField(MetaField metaField){
        int insert = metaFieldMapper.insert(metaField);
        if(insert > 0){
            MetaFieldHistory metaFieldHistory = new MetaFieldHistory();
            BeanUtils.copyProperties(metaField,metaFieldHistory);
            metaFieldHistory.setId(metaFieldMapper.selectLastId());
            metaFieldHistoryMapper.insert(metaFieldHistory);
        }
        return insert;
    }

    @Override
    public int saveOrUpdateMetaField(MetaField metaField) {

        if(metaField.getId() == null){
            metaFieldMapper.insert(metaField);
        }else {
            metaFieldMapper.updateById(metaField);
        }
        MetaFieldHistory metaFieldHistory = new MetaFieldHistory();
        BeanUtils.copyProperties(metaField,metaFieldHistory);
        metaFieldHistory.setId(metaField.getId() == null?metaFieldMapper.selectLastId():metaField.getId());
        metaFieldHistoryMapper.insert(metaFieldHistory);
        return 1;
    }

    @Override
    public MetaField findOne(Integer id){
        return metaFieldMapper.selectById(id);
    }
}
